package com.itheima.filter;


import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

@Slf4j
@WebFilter
public class TokenFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转化http请求对象
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        String requestURI = httpRequest.getRequestURI();
        if (requestURI.contains("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取请求投的token
        String token = httpRequest.getHeader("token");
        //判断token是否为空
        if (token == null){
            log.info("token为空，未登录");
            httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
        }catch(Exception e){
            log.error("token解析失败",e);
            httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        log.info("token解析成功，放行");
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
